package com.jokerx.ohos.fasttrpg.slice;

import com.jokerx.ohos.fasttrpg.MainAbility;
import com.jokerx.ohos.fasttrpg.ResourceTable;
import com.jokerx.ohos.fasttrpg.gamemaster.GameMasterServiceRemoteProxy;
import com.jokerx.ohos.fasttrpg.play.PlayAbility;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.ability.continuation.*;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.bundle.ElementName;
import ohos.distributedschedule.interwork.DeviceManager;
import ohos.distributedschedule.interwork.IInitCallback;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.IRemoteObject;
import ohos.rpc.RemoteException;

public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.DEBUG, 0x0, MainAbility.class.getName());
    /**
     * 流转任务管理服务管理类
     */
    private IContinuationRegisterManager continuationRegisterManager;

    /**
     * 注册流转任务管理服务后返回的Ability token
     */
    private int abilityToken;

    /**
     * 设置初始化分布式环境的回调
     */
    private IInitCallback iInitCallback = new IInitCallback() {
        @Override
        public void onInitSuccess(String deviceId) {
            HiLog.info(TAG, "device id success: " + deviceId);
        }

        @Override
        public void onInitFailure(String deviceId, int errorCode) {
            HiLog.info(TAG, "device id failed: " + deviceId + "errorCode: " + errorCode);
        }
    };

    /**
     * 设置流转任务管理服务设备状态变更的回调
     */
    private IContinuationDeviceCallback iContinuationDeviceCallback = new IContinuationDeviceCallback() {
        @Override
        public void onConnected(ContinuationDeviceInfo deviceInfo) {
            // 在用户选择设备后设置设备ID
            String selectDeviceId = deviceInfo.getDeviceId();
            try {
                // 初始化分布式环境
                DeviceManager.initDistributedEnvironment(selectDeviceId, iInitCallback);
            } catch (RemoteException e) {
                HiLog.info(TAG, "initDistributedEnvironment failed");
            }
            //更新选择设备后的流转状态
            continuationRegisterManager.updateConnectStatus(abilityToken, selectDeviceId, DeviceConnectState.CONNECTED.getState(), null);
            startRemoteAbility(selectDeviceId);
        }

        @Override
        public void onDisconnected(String deviceId) {
        }

        @Override
        public void onDeviceConnectDone(String s, String s1) {

        }

        @Override
        public void onDeviceDisconnectDone(String s) {

        }
    };

    /**
     * 设置注册流转任务管理服务回调
     */
    private RequestCallback requestCallback = new RequestCallback() {
        @Override
        public void onResult(int result) {
            abilityToken = result;
        }
    };

    private GameMasterServiceRemoteProxy gameMasterServiceRemoteProxy;

    // 创建连接GameMasterService回调实例
    private IAbilityConnection connection = new IAbilityConnection() {
        // 连接到Service的回调
        @Override
        public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int resultCode) {
            HiLog.info(TAG, "elementName=%{public}s, iRemoteObject=%{public}s, resultCode=%{public}s", elementName, iRemoteObject,
                    resultCode);
            // Client侧需要定义与Service侧相同的IRemoteObject实现类。开发者获取服务端传过来IRemoteObject对象，并从中解析出服务端传过来的信息。
            gameMasterServiceRemoteProxy = new GameMasterServiceRemoteProxy(iRemoteObject);
        }

        // Service异常死亡的回调
        @Override
        public void onAbilityDisconnectDone(ElementName elementName, int resultCode) {
        }
    };

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        // 获取权限
        requestPermissionsFromUser(new String[]{"ohos.permission.DISTRIBUTED_DATASYNC"}, 0);
        // 获取流转任务管理服务管理类
        this.continuationRegisterManager = getContinuationRegisterManager();
        registerContinuation();
        // 初始化View
        initView();
        startGameMaster();
        connectGameMaster();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onStop() {
        super.onStop();
        // 解注册流转任务管理服务
        continuationRegisterManager.unregister(abilityToken, null);
        // 断开流转任务管理服务连接
        continuationRegisterManager.disconnect();
    }

    private void startGameMaster() {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName("com.jokerx.ohos.fasttrpg.gamemaster.GameMasterServiceAbility")
                .build();
        intent.setOperation(operation);
        startAbility(intent);
    }

    private void connectGameMaster() {
        // 连接Service
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName("com.jokerx.ohos.fasttrpg.gamemaster.GameMasterServiceAbility")
                .build();
        intent.setOperation(operation);
        connectAbility(intent, connection);
    }

    private void initView() {
        // 邀请玩家按钮
        Button btnInvite = (Button) findComponentById(ResourceTable.Id_btn_invite);
        btnInvite.setClickedListener(component -> {
            // 设置过滤设备类型
            ExtraParams params = new ExtraParams();
            String[] devTypes = new String[]{ExtraParams.DEVICETYPE_SMART_PAD, ExtraParams.DEVICETYPE_SMART_PHONE};
            params.setDevType(devTypes);
            // 显示选择设备列表
            continuationRegisterManager.showDeviceList(abilityToken, params, null);
        });
        // 开始游戏按钮
        Button btnStartGame = (Button) findComponentById(ResourceTable.Id_btn_start_game);
        btnStartGame.setClickedListener(component -> {
            gameMasterServiceRemoteProxy.startGame();
        });
    }

    /**
     * register Continuation
     */
    private void registerContinuation() {
        //增加过滤条件
        ExtraParams params = new ExtraParams();
        String[] devTypes = new String[]{ExtraParams.DEVICETYPE_SMART_PAD, ExtraParams.DEVICETYPE_SMART_PHONE};
        params.setDevType(devTypes);
        continuationRegisterManager.register(getBundleName(), params, iContinuationDeviceCallback, requestCallback);
    }

    private void startRemoteAbility(String deviceId) {
        // 通过showDeviceList获取指定目标设备deviceId
        // 指定待启动FA/PA的bundleName和abilityName
        // 设置分布式标记，表明当前涉及分布式能力
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId(deviceId)
                .withBundleName(getBundleName())
                .withAbilityName("com.jokerx.ohos.fasttrpg.play.PlayAbility")
                .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                .build();
        Intent startIntent = new Intent();
        startIntent.setOperation(operation);
        startIntent.setParam("masterDeviceId", getOriginalDeviceId());
        // 通过AbilitySlice包含的startAbility接口实现跨设备启动FA/PA
        startAbility(startIntent);
    }

}
